package net.viralpatel.struts2;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.sun.org.apache.xerces.internal.impl.dv.dtd.NMTOKENDatatypeValidator;

public class ChangePasswdAction extends ActionSupport{
	private String currentpasswd;
	private String newpasswd;
	String url = "jdbc:mysql://localhost:3306/";
	String dbName = "t10";
	String driverName = "com.mysql.jdbc.Driver";
	Connection con = null;

	String nameroot = "root";
	String passwordroot = "";
	public String execute() throws Exception{
		String cPassMd5= DigestUtils.md5Hex( this.currentpasswd);
		Map session = ActionContext.getContext().getSession();
		if(session.get("password").toString().equals(cPassMd5) ){
			
			try {
				Class.forName(driverName);
				con = DriverManager.getConnection(url + dbName,nameroot,passwordroot);
			} catch (ClassNotFoundException e) {
				System.out.println(e.getMessage());	
			}catch(Exception e){
				System.out.println(e.getMessage());
			}
			String nPassMd5 = DigestUtils.md5Hex( this.newpasswd);
			String selectChangePasswd = "Update user set password=? where userID =?";
			PreparedStatement prepStmt = con.prepareStatement(selectChangePasswd);
			prepStmt.setString(1, nPassMd5);
			prepStmt.setString(2, session.get("username").toString());
			int row = prepStmt.executeUpdate();
			if(row!=0){
				session.put("passwoed", nPassMd5);
				return SUCCESS;
			}else{
				addActionError(getText("error.changepasswd"));
				return ERROR;
			}
		}else{
			addActionError(getText("error.changepasswd"));
			return ERROR;
		}
	}
	public void setCurrentpasswd(String currentpasswd) {
		this.currentpasswd = currentpasswd;
	}
	public String getCurrentpasswd() {
		return currentpasswd;
	}
	public void setNewpasswd(String newpasswd) {
		this.newpasswd = newpasswd;
	}
	public String getNewpasswd() {
		return newpasswd;
	}
}
